package com.ruoyi.business.controller;

import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.business.domain.PaymentOrder;
import com.ruoyi.business.domain.PaymentResult;
import com.ruoyi.business.service.IPaymentService;


/**
 * @author 22714
 */
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private IPaymentService paymentService;

    // 创建支付订单
    @PostMapping("/createOrder")
    public AjaxResult createPaymentOrder(@RequestBody PaymentOrder order) {
        try {
            String paymentUrl = paymentService.createPaymentOrder(order);
            if (paymentUrl != null) {
                return AjaxResult.success(paymentUrl);
            } else {
                return AjaxResult.error("创建支付订单失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("创建支付订单失败：" + e.getMessage());
        }
    }

    // 处理支付回调
    @PostMapping("/callback")
    public String handlePaymentCallback(@RequestBody String callbackData) {
        try {
            PaymentResult result = paymentService.handlePaymentCallback(callbackData);
            if (result.isSuccess()) {
                return "success";
            } else {
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    // 根据订单号查询支付订单信息（新增接口示例，可按需调整）
    @GetMapping("/order/{orderNo}")
    public AjaxResult selectPaymentOrderByOrderNo(@PathVariable String orderNo) {
        try {
            PaymentOrder paymentOrder = paymentService.selectPaymentOrderByOrderNo(orderNo);
            if (paymentOrder != null) {
                return AjaxResult.success(paymentOrder);
            } else {
                return AjaxResult.error("未找到对应的支付订单");
            }
        } catch (Exception e) {
            return AjaxResult.error("查询支付订单失败：" + e.getMessage());
        }
    }
}